#!/usr/bin/env python

import sys

def hex2bin(src_file, dst_file, byte_num):
    src_fd = open(src_file, "r")
    dat_fd = open(dst_file, "wb")
    line = src_fd.readline()
    byte_cnt = 0
    while line:
        line = line.strip()
        if(len(line) != byte_num*2):
            sys.exit("error")
        data = int(line, 16).to_bytes(byte_num, "little")
        print(data)
        dat_fd.write(data)
        byte_cnt = byte_cnt + byte_num
        line = src_fd.readline()
    src_fd.close()
    dat_fd.close()

if __name__ == "__main__":
    num = 4
    if(len(sys.argv) == 1):
        hex2bin("rom.hex", "rom.bin", num)
    elif(len(sys.argv) == 2):
        hex2bin(sys.argv[1], "rom.bin", num)
    elif(len(sys.argv) == 3):
        hex2bin(sys.argv[1], sys.argv[2], num)
    elif(len(sys.argv) == 4):
        num = int(sys.argv[3])
        hex2bin(sys.argv[1], sys.argv[2], num)
    else :
        sys.exit("error")
